package com.lnlyj.media.ui;

import android.content.Intent;
import android.database.ContentObserver;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.widget.TextView;

import com.lnlyj.media.Config;
import com.lnlyj.media.LnlyjSelector;
import com.lnlyj.media.R;
import com.lnlyj.media.ResultData;
import com.lnlyj.media.base.BaseFragment;
import com.lnlyj.media.data.MediaGroup;
import com.lnlyj.media.data.MediaItem;
import com.lnlyj.media.widget.GalleryRecyclerView;
import com.lnlyj.media.widget.MediaToolBar;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.Nullable;
import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.GridLayoutManager;

import static android.app.Activity.RESULT_CANCELED;
import static android.app.Activity.RESULT_OK;
import static com.lnlyj.media.Constants.EXTRA_CONFIG;
import static com.lnlyj.media.Constants.EXTRA_RESULT_DATA;
import static com.lnlyj.media.Constants.REQUEST_CODE_MEDIA;

/**
 * wanglei 2020-04-16
 */
public class MediaFragment extends BaseFragment {

    public static final String TAG = "MediaFragment";

    private MediaToolBar toolBar;
    private GalleryRecyclerView recyclerView;
    private TextView previewTv;
    private TextView fullImageTv;

    private MediaAdapter adapter;
    private List<MediaGroup> mediaGroups = new ArrayList<>();

    private MediaViewModel viewModel;

    private Config config;


    private ContentObserver imageObserver = new ContentObserver(new Handler()) {
        @Override
        public void onChange(boolean selfChange, Uri uri) {
            super.onChange(selfChange, uri);
            removeCallback(observerRunnable);
            postDelayed(observerRunnable, 500);
        }
    };
    private ContentObserver videoObserver = new ContentObserver(new Handler()) {
        @Override
        public void onChange(boolean selfChange, Uri uri) {
            super.onChange(selfChange, uri);
            removeCallback(observerRunnable);
            postDelayed(observerRunnable, 500);
        }
    };

    public Runnable observerRunnable = () -> {
        viewModel.getAlbumData();
    };

    public static MediaFragment getInstance(boolean isUseLazy, Config config) {
        MediaFragment fragment = new MediaFragment(R.layout.fragment_media, isUseLazy);
        if (config != null) {
            Bundle bundle = new Bundle();
            bundle.putParcelable(EXTRA_CONFIG, config);
            fragment.setArguments(bundle);
        }
        return fragment;
    }


    private MediaFragment(int layoutId, boolean isUseLazy) {
        super(layoutId, isUseLazy);
    }

    public MediaFragment() {
        super();
    }

    @Override
    public void initBundleData() {
        Bundle bundle = getArguments();
        if (bundle != null) {
            config = bundle.getParcelable(EXTRA_CONFIG);
        }
        if (config == null) {
            config = LnlyjSelector.getInstance().getGlobalConfig();
        }
    }

    @Override
    protected void initViewModel() {
        viewModel = ViewModelProviders.of(this).get(MediaViewModel.class);

        viewModel.getMediaLiveData().observe(this, list -> {
            mediaGroups.clear();

            if (list != null && !list.isEmpty()) {
                mediaGroups.addAll(list);
            }

            adapter.swapResult(mediaGroups);
        });

        viewModel.getAlbumLiveData().observe(this, list -> {
            toolBar.setAlbumData(list);
        });
    }

    @Override
    public void initView() {
        recyclerView = findViewById(R.id.recycler_view);
        toolBar = findViewById(R.id.toolbar);
        previewTv = findViewById(R.id.tv_preview);
        fullImageTv = findViewById(R.id.tv_full_image);

        GridLayoutManager manager = new GridLayoutManager(getActivity(), config.getSpanCount());
        recyclerView.setLayoutManager(manager);

        recyclerView.setAdapter(adapter = new MediaAdapter());

        adapter.setOnMediaAdapterClick(new MediaAdapter.OnMediaAdapterClick() {
            @Override
            public void onMediaClick(MediaItem item, int position) {
                AlbumActivity.call(MediaFragment.this, toolBar.getCurrentAlbum().getConfig(), config, position);
            }

            @Override
            public void onSelectClick(MediaItem item) {
                SelectionManager manager = SelectionManager.getInstance();
                if (!manager.contains(item)) {
                    if (manager.getSize() < config.getSelectCount()) {
                        manager.add(item);
                        adapter.notifyDataSetChanged();
                    } else {
                        snackMsg(getString(R.string.toast_max_select, config.getSelectCount()));
                    }
                } else {
                    manager.remove(item);
                    adapter.notifyDataSetChanged();
                }
                checkUI(false);
            }
        });

        toolBar.setCloseListener(()-> setResult(RESULT_CANCELED));

        toolBar.setSelectorListener(()-> {
            finishSelector();
        });

        toolBar.setAlbumChangeListener(item -> {
            viewModel.getMediaData(item.getConfig());
            recyclerView.scrollToPosition(0);
        });

        previewTv.setOnClickListener(view -> {
            AlbumActivity.call(this, null, config, 0);
        });

        fullImageTv.setOnClickListener(view -> {
            fullImageTv.setSelected(!fullImageTv.isSelected());
            SelectionManager.getInstance().setFullImage(fullImageTv.isSelected());
        });

        checkUI(false);
    }

    @Override
    public void initData() {
        if (recyclerView != null) {
            recyclerView.post(observerRunnable);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void setResult(int resultCode, Intent data) {
        super.setResult(resultCode, data);
        SelectionManager.getInstance().clear();
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_MEDIA) {
            checkUI(true);
            if (resultCode == RESULT_OK) {
                setResult(RESULT_OK, data);
            }
        }
    }

    private void checkUI(boolean notifyAdapter) {
        if (notifyAdapter && adapter != null) {
            adapter.notifyDataSetChanged();
        }

        SelectionManager manager = SelectionManager.getInstance();
        int selectSize = manager.getSize();
        String previewText;
        String sendText;

        if (selectSize > 0) {
            previewText = String.format(getString(R.string.media_text_preview) + "(%d)", selectSize);
            sendText = String.format(getString(R.string.media_text_send) + "(%d/%s)", selectSize, config.getSelectCount());
        } else {
            sendText = getString(R.string.media_text_send);
            previewText = getString(R.string.media_text_preview);
        }

        previewTv.setText(previewText);
        previewTv.setEnabled(selectSize > 0);
        toolBar.setSendButtonText(sendText);
        toolBar.setSendButtonEnabled(selectSize > 0);
        fullImageTv.setSelected(SelectionManager.getInstance().isFullImage());
    }

    private void finishSelector() {
        ArrayList<ResultData> items = SelectionManager.getInstance().getResultData();
        Intent intent = new Intent();
        intent.putParcelableArrayListExtra(EXTRA_RESULT_DATA, items);
        setResult(RESULT_OK, intent);
    }
}
